package net.paruo.google.gwt.study_meeting.user_control.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class UserSearch extends Composite {

	private static UserSearchUiBinder uiBinder = GWT
			.create(UserSearchUiBinder.class);

	interface UserSearchUiBinder extends UiBinder<Widget, UserSearch> {
	}

	@UiField
	TextBox tbSearch;
	@UiField
	FlowPanel panel;

	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);
	private final HTML message;

	public UserSearch() {
		initWidget(uiBinder.createAndBindUi(this));
		message = new HTML("");
		panel.add(message);
	}

	@UiHandler("tbSearch")
	void onKeyUp(KeyUpEvent e) {
		final String userName = tbSearch.getText().trim();
		if ("".equals(userName)) {
			panel.clear();
			message.setHTML("");
			panel.add(message);
			return;
		}
		greetingService.searchUser(userName,
				new AsyncCallback<List<UserData>>() {

					@Override
					public void onSuccess(List<UserData> result) {
						if (result.isEmpty()) {
							panel.clear();
							message.setHTML("該当するユーザが見つかりません。");
							panel.add(message);
							return;
						}

						panel.clear();
						for (UserData data : result) {
							UserAnchor a = new UserAnchor(data);
							panel.add(a);
						}
					}

					@Override
					public void onFailure(Throwable caught) {
						panel.clear();
						message.setHTML("エラーが発生しました。");
						panel.add(message);
						GWT.log("Error occurred while searching: " + userName,
								caught);
					}
				});
	}

}
